Perl vs. Ruby on Two Idioms

Shlomi Fish on 2008-05-22T10:22:57

I've been meaning to blog about it for a few weeks, so here goes. In a Ruby-Israel thread someone asked how to convert an array to a hash that contains all of its keys as members (and "true" as a value). They came up with:

a = [1, 2, 3, 'other']
h = a.inject({}) {|h, v| h[v] = true; h } 

In Perl, it's:

@a = (1,2,3, 'other');
my %h = (map { $_ => 1 } @a);

Much cleaner. I also though of a way to do a flat concatenation of an array of array references. Like [[1,2,3],[4,5,6],[7,["One", "Two",],9]] into [1,2,3,4,5,6,7,["One", "Two",],9]. In Ruby it is:

[[1,2],[3,4],[5,6,["Hello","There"],7]].inject([]) { |a,e| a+e }

While in Perl it is:

(map { @$_ } ([1,2],[3,4],[5,6,["Hello","There",],7]))

Both of these are caused by the fact that lists are not references in Perl, and that one can initialise arrays and hashes from them. This is while in Ruby or Python (and most Lisps) they are references. That or Ruby lacks more primitives.


Perl is still concise

deepfryed on 2008-05-24T00:27:23

You can do

h = Hash[*([1,2,3].zip([4,5,6]).flatten)]

but tis still not going to beat

%h = qw(1 4 2 5 3 6);

Re:Perl is still concise

deepfryed on 2008-05-24T00:30:45

silly me,

what I meant was

@h{qw(1 2 3)} = qw(4 5 6);

I need to go get a coffee